package com.hunray.rent.dao;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.repository.core.RepositoryMetadata;

public class BaseDaoFactory extends JpaRepositoryFactory {

	private final EntityManager em;

	public BaseDaoFactory(EntityManager entityManager) {
		super(entityManager);
		this.em = entityManager;
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Object getTargetRepository(RepositoryMetadata metadata) {
		if (IBaseDao.class.isAssignableFrom(metadata.getRepositoryInterface())) {
			JpaEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata
					.getDomainType());
			BaseDao<?, Serializable> repository = new BaseDao(
					entityInformation, em);
			return repository;
		}
		return super.getTargetRepository(metadata);
	}

	@Override
	protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
		if (IBaseDao.class.isAssignableFrom(metadata.getRepositoryInterface())) {
			return BaseDao.class;
		}
		return super.getRepositoryBaseClass(metadata);
	}

}
